package com.itjin.resume_back.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itjin.resume_back.common.Result;
import com.itjin.resume_back.entity.Project;
import com.itjin.resume_back.service.ProjectService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 项目控制器
 * 提供项目相关的接口，包括创建、更新、删除、查询等功能
 */
@Tag(name = "项目管理", description = "项目相关的接口，包括创建、更新、删除、查询等功能")
@RestController
@RequestMapping("/api/project")
@RequiredArgsConstructor
public class ProjectController {

  private final ProjectService projectService;

  /**
   * 创建项目
   * 
   * @param userId      用户ID
   * @param name        项目名称
   * @param description 项目描述
   * @param techStack   技术栈
   * @param file        项目文件
   * @return 操作结果
   */
  @Operation(summary = "创建项目", description = "创建新项目，上传项目文件")
  @PostMapping("/create")
  public Result<String> createProject(
      @Parameter(description = "用户ID", required = true) @RequestParam("userId") Long userId,
      @Parameter(description = "项目名称", required = true) @RequestParam("name") String name,
      @Parameter(description = "项目描述", required = true) @RequestParam("description") String description,
      @Parameter(description = "技术栈", required = true) @RequestParam("techStack") String techStack,
      @Parameter(description = "项目文件", required = true) @RequestParam("file") MultipartFile file) {
    try {
      projectService.createProject(userId, name, description, techStack, file);
      return Result.success("项目创建成功");
    } catch (Exception e) {
      return Result.error(e.getMessage());
    }
  }

  /**
   * 更新项目
   * 
   * @param id          项目ID
   * @param name        项目名称
   * @param description 项目描述
   * @param techStack   技术栈
   * @param file        项目文件（可选）
   * @return 操作结果
   */
  @Operation(summary = "更新项目", description = "更新项目信息，可选择是否更新项目文件")
  @PutMapping("/update")
  public Result<String> updateProject(
      @Parameter(description = "项目ID", required = true) @RequestParam("id") Long id,
      @Parameter(description = "项目名称", required = true) @RequestParam("name") String name,
      @Parameter(description = "项目描述", required = true) @RequestParam("description") String description,
      @Parameter(description = "技术栈", required = true) @RequestParam("techStack") String techStack,
      @Parameter(description = "项目文件", required = false) @RequestParam(value = "file", required = false) MultipartFile file) {
    try {
      projectService.updateProject(id, name, description, techStack, file);
      return Result.success("项目更新成功");
    } catch (Exception e) {
      return Result.error(e.getMessage());
    }
  }

  /**
   * 删除项目
   * 
   * @param id 项目ID
   * @return 操作结果
   */
  @Operation(summary = "删除项目", description = "删除指定项目")
  @DeleteMapping("/delete")
  public Result<String> deleteProject(
      @Parameter(description = "项目ID", required = true) @RequestParam("id") Long id) {
    try {
      projectService.deleteProject(id);
      return Result.success("项目删除成功");
    } catch (Exception e) {
      return Result.error(e.getMessage());
    }
  }

  /**
   * 获取项目列表
   * 
   * @param userId 用户ID
   * @param page   页码
   * @param size   每页大小
   * @return 分页项目列表
   */
  @Operation(summary = "获取项目列表", description = "分页获取用户的项目列表")
  @GetMapping("/list")
  public Result<Page<Project>> listProjects(
      @Parameter(description = "用户ID", required = true) @RequestParam("userId") Long userId,
      @Parameter(description = "页码", required = true) @RequestParam(value = "page", defaultValue = "1") Integer page,
      @Parameter(description = "每页大小", required = true) @RequestParam(value = "size", defaultValue = "10") Integer size) {
    try {
      Page<Project> pageParam = new Page<>(page, size);
      LambdaQueryWrapper<Project> wrapper = new LambdaQueryWrapper<>();
      wrapper.eq(Project::getUserId, userId);
      wrapper.orderByDesc(Project::getCreateTime);
      Page<Project> projectPage = projectService.page(pageParam, wrapper);
      return Result.success(projectPage);
    } catch (Exception e) {
      return Result.error(e.getMessage());
    }
  }

  /**
   * 获取项目详情
   * 
   * @param id 项目ID
   * @return 项目详情
   */
  @Operation(summary = "获取项目详情", description = "获取指定项目的详细信息")
  @GetMapping("/detail")
  public Result<Project> getProjectDetail(
      @Parameter(description = "项目ID", required = true) @RequestParam("id") Long id) {
    try {
      Project project = projectService.getById(id);
      if (project != null) {
        return Result.success(project);
      } else {
        return Result.error("项目不存在");
      }
    } catch (Exception e) {
      return Result.error(e.getMessage());
    }
  }

  /**
   * 下载项目文件
   * 
   * @param id 项目ID
   * @return 项目文件
   */
  @Operation(summary = "下载项目文件", description = "下载指定项目的文件")
  @GetMapping("/download")
  public ResponseEntity<byte[]> downloadProject(
      @Parameter(description = "项目ID", required = true) @RequestParam("id") Long id) {
    try {
      Project project = projectService.getById(id);
      if (project == null) {
        return ResponseEntity.notFound().build();
      }

      byte[] fileData = projectService.getProjectFile(id);

      // 获取文件扩展名
      String fileUrl = project.getFileUrl();
      String fileExtension = fileUrl.substring(fileUrl.lastIndexOf("."));

      // 根据文件扩展名设置Content-Type
      MediaType mediaType;
      if (".zip".equalsIgnoreCase(fileExtension)) {
        mediaType = MediaType.parseMediaType("application/zip");
      } else if (".rar".equalsIgnoreCase(fileExtension)) {
        mediaType = MediaType.parseMediaType("application/x-rar-compressed");
      } else if (".7z".equalsIgnoreCase(fileExtension)) {
        mediaType = MediaType.parseMediaType("application/x-7z-compressed");
      } else {
        mediaType = MediaType.APPLICATION_OCTET_STREAM;
      }

      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(mediaType);
      // 设置文件名，使用URL编码确保中文文件名正确显示
      String encodedFileName = java.net.URLEncoder.encode(project.getName() + fileExtension, "UTF-8")
          .replaceAll("\\+", "%20");
      headers.setContentDispositionFormData("attachment", encodedFileName);
      headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
      headers.setContentLength(fileData.length);

      // 增加下载次数
      projectService.incrementDownloadCount(id);

      return ResponseEntity.ok()
          .headers(headers)
          .body(fileData);
    } catch (Exception e) {
      return ResponseEntity.badRequest().build();
    }
  }
}